import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "motion/react";
import { Button } from "./ui/button";
import { Card } from "./ui/card";
import { Badge } from "./ui/badge";
import { Input } from "./ui/input";
import {
	Search,
	Plus,
	Trash2,
	MessageSquare,
	Clock,
	User,
	Bot,
	Star,
	Archive,
	Filter,
	MoreHorizontal,
	Edit3,
	Share2,
} from "lucide-react";
import { ChatSession } from "./Sidebar";

interface SessionManagerProps {
	sessions: ChatSession[];
	currentSessionId?: string;
	onSessionSelect: (sessionId: string) => void;
	onNewSession: () => void;
	onDeleteSession: (sessionId: string) => void;
	onRenameSession?: (sessionId: string, newTitle: string) => void;
	onArchiveSession?: (sessionId: string) => void;
	onStarSession?: (sessionId: string) => void;
	onShareSession?: (sessionId: string) => void;
}

interface SessionGroup {
	title: string;
	sessions: ChatSession[];
}

export function SessionManager({
	sessions,
	currentSessionId,
	onSessionSelect,
	onNewSession,
	onDeleteSession,
	onRenameSession,
	onArchiveSession,
	onStarSession,
	onShareSession,
}: SessionManagerProps) {
	const [searchQuery, setSearchQuery] = useState("");
	const [filterType, setFilterType] = useState<"all" | "starred" | "archived">(
		"all",
	);
	const [editingSessionId, setEditingSessionId] = useState<string | null>(null);
	const [editingTitle, setEditingTitle] = useState("");
	const [showSessionActions, setShowSessionActions] = useState<string | null>(
		null,
	);

	// 过滤会话
	const filteredSessions = sessions.filter((session) => {
		const matchesSearch =
			session.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
			session.lastMessage.toLowerCase().includes(searchQuery.toLowerCase()) ||
			session.agentName?.toLowerCase().includes(searchQuery.toLowerCase());

		// 这里可以根据 filterType 进一步过滤
		return matchesSearch;
	});

	// 按时间分组会话
	const groupSessionsByTime = (sessions: ChatSession[]): SessionGroup[] => {
		const now = new Date();
		const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
		const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
		const monthAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);

		const groups: SessionGroup[] = [
			{ title: "今天", sessions: [] },
			{ title: "昨天", sessions: [] },
			{ title: "本周", sessions: [] },
			{ title: "本月", sessions: [] },
			{ title: "更早", sessions: [] },
		];

		sessions.forEach((session) => {
			const sessionDate = new Date(session.timestamp);

			if (sessionDate >= today) {
				groups[0].sessions.push(session);
			} else if (sessionDate >= yesterday) {
				groups[1].sessions.push(session);
			} else if (sessionDate >= weekAgo) {
				groups[2].sessions.push(session);
			} else if (sessionDate >= monthAgo) {
				groups[3].sessions.push(session);
			} else {
				groups[4].sessions.push(session);
			}
		});

		return groups.filter((group) => group.sessions.length > 0);
	};

	const sessionGroups = groupSessionsByTime(filteredSessions);

	// 格式化时间
	const formatTime = (date: Date) => {
		const now = new Date();
		const diff = now.getTime() - new Date(date).getTime();
		const days = Math.floor(diff / (1000 * 60 * 60 * 24));

		if (days === 0) {
			return date.toLocaleTimeString("zh-CN", {
				hour: "2-digit",
				minute: "2-digit",
			});
		} else if (days === 1) {
			return "昨天";
		} else if (days < 7) {
			return `${days}天前`;
		} else {
			return date.toLocaleDateString("zh-CN", {
				month: "short",
				day: "numeric",
			});
		}
	};

	// 开始编辑会话标题
	const startEditingTitle = (session: ChatSession) => {
		setEditingSessionId(session.id);
		setEditingTitle(session.title);
		setShowSessionActions(null);
	};

	// 保存编辑的标题
	const saveEditedTitle = () => {
		if (editingSessionId && editingTitle.trim() && onRenameSession) {
			onRenameSession(editingSessionId, editingTitle.trim());
		}
		setEditingSessionId(null);
		setEditingTitle("");
	};

	// 取消编辑
	const cancelEditing = () => {
		setEditingSessionId(null);
		setEditingTitle("");
	};

	return (
		<div className="h-full flex flex-col">
			{/* 头部 */}
			<div className="p-4 border-b border-slate-200 dark:border-slate-700">
				<div className="flex items-center justify-between mb-4">
					<h2 className="text-lg font-semibold text-slate-900 dark:text-white">
						会话记录
					</h2>
					<Button onClick={onNewSession} size="sm">
						<Plus className="w-4 h-4 mr-2" />
						新建
					</Button>
				</div>

				{/* 搜索框 */}
				<div className="relative mb-3">
					<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
					<Input
						value={searchQuery}
						onChange={(e) => setSearchQuery(e.target.value)}
						placeholder="搜索会话..."
						className="pl-10"
					/>
				</div>

				{/* 过滤器 */}
				<div className="flex gap-2">
					{[
						{ key: "all", label: "全部", icon: MessageSquare },
						{ key: "starred", label: "收藏", icon: Star },
						{ key: "archived", label: "归档", icon: Archive },
					].map(({ key, label, icon: Icon }) => (
						<Button
							key={key}
							variant={filterType === key ? "default" : "outline"}
							size="sm"
							onClick={() => setFilterType(key as any)}
							className="flex-1"
						>
							<Icon className="w-3 h-3 mr-1" />
							{label}
						</Button>
					))}
				</div>
			</div>

			{/* 会话列表 */}
			<div className="flex-1 overflow-y-auto p-2">
				{sessionGroups.length === 0 ? (
					<div className="text-center text-slate-400 mt-8">
						{searchQuery ? "未找到匹配的会话" : "暂无会话记录"}
					</div>
				) : (
					<div className="space-y-4">
						{sessionGroups.map((group) => (
							<div key={group.title}>
								<h3 className="text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2 px-2">
									{group.title}
								</h3>
								<div className="space-y-1">
									{group.sessions.map((session) => (
										<motion.div
											key={session.id}
											initial={{ opacity: 0, y: 10 }}
											animate={{ opacity: 1, y: 0 }}
											className="group relative"
										>
											<Card
												className={`p-3 cursor-pointer transition-all duration-200 hover:shadow-md ${
													currentSessionId === session.id
														? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800"
														: "hover:bg-slate-50 dark:hover:bg-slate-800/50"
												}`}
												onClick={() => onSessionSelect(session.id)}
											>
												<div className="flex items-start justify-between">
													<div className="flex-1 min-w-0">
														{/* 会话标题 */}
														{editingSessionId === session.id ? (
															<div className="flex items-center gap-2 mb-2">
																<Input
																	value={editingTitle}
																	onChange={(e) =>
																		setEditingTitle(e.target.value)
																	}
																	onKeyDown={(e) => {
																		if (e.key === "Enter") {
																			saveEditedTitle();
																		} else if (e.key === "Escape") {
																			cancelEditing();
																		}
																	}}
																	onBlur={saveEditedTitle}
																	className="text-sm"
																	autoFocus
																/>
															</div>
														) : (
															<h4 className="text-sm font-medium text-slate-900 dark:text-white truncate mb-1">
																{session.title}
															</h4>
														)}

														{/* 最后一条消息 */}
														<p className="text-xs text-slate-500 dark:text-slate-400 truncate mb-2">
															{session.lastMessage}
														</p>

														{/* 底部信息 */}
														<div className="flex items-center justify-between">
															<div className="flex items-center gap-2">
																{session.agentName && (
																	<Badge variant="outline" className="text-xs">
																		<Bot className="w-3 h-3 mr-1" />
																		{session.agentName}
																	</Badge>
																)}
																<div className="flex items-center gap-1 text-xs text-slate-400">
																	<MessageSquare className="w-3 h-3" />
																	<span>{session.messageCount}</span>
																</div>
															</div>

															<div className="flex items-center gap-2">
																<span className="text-xs text-slate-400">
																	{formatTime(session.timestamp)}
																</span>
															</div>
														</div>
													</div>

													{/* 操作按钮 */}
													<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
														<Button
															variant="ghost"
															size="sm"
															onClick={(e) => {
																e.stopPropagation();
																setShowSessionActions(
																	showSessionActions === session.id
																		? null
																		: session.id,
																);
															}}
															className="h-6 w-6 p-0"
														>
															<MoreHorizontal className="w-3 h-3" />
														</Button>
													</div>
												</div>

												{/* 操作菜单 */}
												<AnimatePresence>
													{showSessionActions === session.id && (
														<motion.div
															initial={{ opacity: 0, scale: 0.95 }}
															animate={{ opacity: 1, scale: 1 }}
															exit={{ opacity: 0, scale: 0.95 }}
															className="absolute right-2 top-12 bg-white dark:bg-slate-800 rounded-lg shadow-lg border border-slate-200 dark:border-slate-700 p-1 z-10"
														>
															<Button
																variant="ghost"
																size="sm"
																onClick={(e) => {
																	e.stopPropagation();
																	startEditingTitle(session);
																}}
																className="w-full justify-start text-xs"
															>
																<Edit3 className="w-3 h-3 mr-2" />
																重命名
															</Button>
															{onStarSession && (
																<Button
																	variant="ghost"
																	size="sm"
																	onClick={(e) => {
																		e.stopPropagation();
																		onStarSession(session.id);
																		setShowSessionActions(null);
																	}}
																	className="w-full justify-start text-xs"
																>
																	<Star className="w-3 h-3 mr-2" />
																	收藏
																</Button>
															)}
															{onShareSession && (
																<Button
																	variant="ghost"
																	size="sm"
																	onClick={(e) => {
																		e.stopPropagation();
																		onShareSession(session.id);
																		setShowSessionActions(null);
																	}}
																	className="w-full justify-start text-xs"
																>
																	<Share2 className="w-3 h-3 mr-2" />
																	分享
																</Button>
															)}
															{onArchiveSession && (
																<Button
																	variant="ghost"
																	size="sm"
																	onClick={(e) => {
																		e.stopPropagation();
																		onArchiveSession(session.id);
																		setShowSessionActions(null);
																	}}
																	className="w-full justify-start text-xs"
																>
																	<Archive className="w-3 h-3 mr-2" />
																	归档
																</Button>
															)}
															<Button
																variant="ghost"
																size="sm"
																onClick={(e) => {
																	e.stopPropagation();
																	onDeleteSession(session.id);
																	setShowSessionActions(null);
																}}
																className="w-full justify-start text-xs text-red-600 hover:text-red-700"
															>
																<Trash2 className="w-3 h-3 mr-2" />
																删除
															</Button>
														</motion.div>
													)}
												</AnimatePresence>
											</Card>
										</motion.div>
									))}
								</div>
							</div>
						))}
					</div>
				)}
			</div>

			{/* 底部统计 */}
			<div className="p-4 border-t border-slate-200 dark:border-slate-700">
				<div className="text-xs text-slate-500 dark:text-slate-400 text-center">
					共 {sessions.length} 个会话
					{searchQuery && ` • 找到 ${filteredSessions.length} 个匹配项`}
				</div>
			</div>
		</div>
	);
}

